package com.zz.bsea.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zz.bsea.entity.Product;
import com.zz.bsea.web.jdbc.JDBCBasic;


public class ProductService {
	
	
	
	public boolean add(Product prod){
	
		boolean flag=false;
		String sql="insert into tb_product(name,category,price,createdby) values (?,?,?,?)";
		Connection conn=JDBCBasic.getConnection();
		try {
			PreparedStatement st=conn.prepareStatement(sql);
			st.setString(1, prod.getName());
			st.setString(2, prod.getCategory());
			st.setDouble(3, prod.getPrice());
			st.setString(4, prod.getCreatedby());
			if(st.executeUpdate()>0) {
				flag=true;
			};
			
			
			JDBCBasic.closeConn(st, null, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return flag;
	}
	
	
	public List<Product> showAll(){
		List<Product> ls=new ArrayList();
		String sql="select * from tb_Product";
		Connection conn=JDBCBasic.getConnection();
		try {
			Statement st=conn.createStatement();
			ResultSet  rs=st.executeQuery(sql);
			//如果ResultSet里面没有记录的时候，就返回fase
			//切勿 打印next方法，如果打印就相当于跳过一条记录
			//System.out.println(rs.next());
			while(rs.next()) {
				Product product=new Product();
				product.setId(rs.getInt("id"));
				product.setName(rs.getString("name"));
				product.setCategory(rs.getString("category"));
				product.setPrice(rs.getDouble("price"));
				ls.add(product);
			}
			
			JDBCBasic.closeConn(st, rs, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ls;
	}
}
